package com.xudm.cdg.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.Tables;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.xudm.cdg.entity.cosmic.CosmicExcelModel;
import com.xudm.cdg.entity.cosmic.SequenceDescription;
import com.xudm.cdg.entity.cosmic.UserInteractionFunction;
import com.xudm.cdg.entity.cosmic.UserInteractiveContent;
import com.xudm.cdg.entity.enumerate.DataMoveTypeEnum;
import com.xudm.cdg.listener.CosmicExcelModelDataListener;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * EasyExcelUtil
 *
 * @author xudm
 */
@Slf4j
public class EasyExcelUtil {

    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("D:\\DevelopSpace\\XW_Space\\workspace\\COSMIC\\COSMIC编写\\二阶段\\宋涛-2024年云南铁通网格运营管理【产品二阶段】.xlsx");
        CosmicExcelModelDataListener listener = new CosmicExcelModelDataListener();
        EasyExcel.read(fis, CosmicExcelModel.class, listener).extraRead(CellExtraTypeEnum.MERGE).sheet().headRowNumber(1).doRead();
        List<CosmicExcelModel> dataList = listener.getDataList();
        // 从CosmicExcelModel对象列表中提取第一层级的数据
        // 然后创建相应的数据列表用于存储下一层级的数据
        Map<String, List<CosmicExcelModel>> collect1 = dataList.stream().collect(Collectors.groupingBy(CosmicExcelModel::getModelName));
        List<Map<String, Object>> dataList1 = new ArrayList<>();
        collect1.forEach((k1, v1) -> {
            // 从第一层级的数据中提取第二层级的数据
            // 然后创建相应的数据列表用于存储下一层级的数据
            List<Map<String, Object>> dataList2 = new ArrayList<>();
            Map<String, Object> dataMap1 = new HashMap<>();
            dataMap1.put("title1", k1);
            dataMap1.put("dataList2", dataList2);
            dataList1.add(dataMap1);
            Map<String, List<CosmicExcelModel>> collect2 = v1.stream().collect(Collectors.groupingBy(CosmicExcelModel::getCustomerDemand));
            collect2.forEach((k2, v2) -> {
                // 从第二层级的数据中提取第三层级的数据
                // 然后创建相应的数据列表用于存储下一层级的数据
                List<Map<String, Object>> dataList3 = new ArrayList<>();
                Map<String, Object> dataMap2 = new HashMap<>();
                dataMap2.put("title2", k2);
                dataMap2.put("dataList3", dataList3);
                dataList2.add(dataMap2);
                Map<String, List<CosmicExcelModel>> collect3 = v2.stream().collect(Collectors.groupingBy(CosmicExcelModel::getFunctionalUserDemand));
                collect3.forEach((k3, v3) -> {
                    List<Map<String, Object>> dataList4 = new ArrayList<>();
                    Map<String, Object> dataMap3 = new HashMap<>();
                    dataMap3.put("title3", k3);
                    dataMap3.put("dataList4", dataList4);
                    dataList3.add(dataMap3);
                    // 从第三层级的数据中提取第四层级的数据
                    v3.stream().collect(Collectors.groupingBy(CosmicExcelModel::getFunctionalProcessing)).forEach((k4, v4) -> {
                        CosmicExcelModel cosmicExcelModelStart = v4.get(0);
                        Map<String, Object> dataMap4 = new HashMap<>();
                        dataMap4.put("title4", k4);
                        //构建详细数据
                        //1、 功能详细描述
                        dataMap4.put("featureDescription", k4);
                        //2、功能界面原型
                        //dataMap4.put("featureInput", cosmicExcelModelStart.getFunctionalInput());
                        //3、用户交互内容
                        List<UserInteractiveContent> uicList = new ArrayList<>();
                        List<CosmicExcelModel> cosmicExcelModelList = v4.stream().filter(cosmicExcelModel -> cosmicExcelModel.getDataMovementType().equalsIgnoreCase("E")).collect(Collectors.toList());
                        for (int i = 0; i < cosmicExcelModelList.size(); i++) {
                            CosmicExcelModel cosmicExcelModel = cosmicExcelModelList.get(i);
                            UserInteractiveContent uic = new UserInteractiveContent();
                            uic.setNumber((i + 1) + "");
                            uic.setDesignation(cosmicExcelModel.getSubFunctionalProcessing());
                            uic.setType("请求");
                            uic.setDescription(cosmicExcelModel.getTriggerEvent());
                            uicList.add(uic);
                        }
                        dataMap4.put("uicList", uicList);

                        //4、用户交互功能
                        List<UserInteractionFunction> uifList = new ArrayList<>();
                        for (int i = 0; i < v4.size(); i++) {
                            CosmicExcelModel cosmicExcelModel = v4.get(i);
                            UserInteractionFunction uic = new UserInteractionFunction();
                            uic.setNumber((i + 1) + "");
                            uic.setDesignation(cosmicExcelModel.getSubFunctionalProcessing());
                            String type = DataMoveTypeEnum.valueOf(cosmicExcelModel.getDataMovementType().toUpperCase()).getValue();
                            uic.setType(type);
                            uic.setDescription(cosmicExcelModel.getTriggerEvent());
                            uifList.add(uic);
                        }
                        dataMap4.put("uifList", uifList);

                        //5、功能交互流程
                        // 提取发起者
                        String initiator = SequenceDescriptionUtil.extractInitiator(cosmicExcelModelStart.getFunctionalUser());
                        dataMap4.put("initiator", StrUtil.isNotBlank(initiator) ? initiator.replace("\n", "") : "");
                        // 提取接收者
                        String receiver = SequenceDescriptionUtil.extractReceiver(cosmicExcelModelStart.getFunctionalUser());
                        dataMap4.put("receiver", StrUtil.isNotBlank(receiver) ? receiver.replace("\n", "") : "");
                        // 提取触发事件
                        String triggerEvent = cosmicExcelModelStart.getTriggerEvent();
                        dataMap4.put("triggerEvent", triggerEvent);
                        // 构建时序图
                        Object[] objects = PlantumlUtil.buildUmlSourceAndDescription(v4);
                        String unlSource = (String) objects[0];
                        List<SequenceDescription> descriptions = (List<SequenceDescription>) objects[1];
                        String sequenceDescription = SequenceDescriptionUtil.getSequenceDescription(descriptions);
                        InputStream inputStream = PlantumlUtil.getInputStream(unlSource);
                        // 插入时序图
                        dataMap4.put("timeSequenceDiagram", Pictures.ofStream(inputStream, PictureType.PNG).create());
                        // 插入时序图描述
                        dataMap4.put("sequenceDescription", sequenceDescription);

                        dataList4.add(dataMap4);
                    });
                });
            });
        });

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList1", dataList1);

        //表格行循环
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("uicList", policy).bind("uifList", policy).build();

        XWPFTemplate template = XWPFTemplate.compile("D:\\DevelopSpace\\XW_Space\\workspace\\COSMIC\\template\\word_template.docx", config).render(dataMap);
        template.writeAndClose(new FileOutputStream("D:\\DevelopSpace\\XW_Space\\workspace\\COSMIC\\template\\COSMIC文档生成-" + LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".docx"));
    }


    /**
     * 读取Excel并生成Word
     *
     * @param file         Excel文件
     * @param outputStream 输出流
     * @throws IOException io异常
     */
    public static void readExcelAndWriter(MultipartFile file, OutputStream outputStream) throws IOException {
        FileInputStream fis = new FileInputStream("D:\\DevelopSpace\\XW_Space\\workspace\\COSMIC\\COSMIC编写\\二阶段\\徐道满-2024年云南铁通网格运营管理【产品二阶段】.xlsx");
//        InputStream fis = file.getInputStream();
        CosmicExcelModelDataListener listener = new CosmicExcelModelDataListener();
        EasyExcel.read(fis, CosmicExcelModel.class, listener).extraRead(CellExtraTypeEnum.MERGE).sheet().headRowNumber(1).doRead();
        List<CosmicExcelModel> dataList = listener.getDataList();
        // 从CosmicExcelModel对象列表中提取第一层级的数据
        // 然后创建相应的数据列表用于存储下一层级的数据
        Map<String, List<CosmicExcelModel>> collect1 = dataList.stream().collect(Collectors.groupingBy(CosmicExcelModel::getModelName));
        List<Map<String, Object>> dataList1 = new ArrayList<>();
        collect1.forEach((k1, v1) -> {
            // 从第一层级的数据中提取第二层级的数据
            // 然后创建相应的数据列表用于存储下一层级的数据
            List<Map<String, Object>> dataList2 = new ArrayList<>();
            Map<String, Object> dataMap1 = new HashMap<>();
            dataMap1.put("title1", k1);
            dataMap1.put("dataList2", dataList2);
            dataList1.add(dataMap1);
            Map<String, List<CosmicExcelModel>> collect2 = v1.stream().collect(Collectors.groupingBy(CosmicExcelModel::getCustomerDemand));
            collect2.forEach((k2, v2) -> {
                // 从第二层级的数据中提取第三层级的数据
                // 然后创建相应的数据列表用于存储下一层级的数据
                List<Map<String, Object>> dataList3 = new ArrayList<>();
                Map<String, Object> dataMap2 = new HashMap<>();
                dataMap2.put("title2", k2);
                dataMap2.put("dataList3", dataList3);
                dataList2.add(dataMap2);
                Map<String, List<CosmicExcelModel>> collect3 = v2.stream().collect(Collectors.groupingBy(CosmicExcelModel::getFunctionalUserDemand));
                collect3.forEach((k3, v3) -> {
                    List<Map<String, Object>> dataList4 = new ArrayList<>();
                    Map<String, Object> dataMap3 = new HashMap<>();
                    dataMap3.put("title3", k3);
                    dataMap3.put("dataList4", dataList4);
                    dataList3.add(dataMap3);
                    // 从第三层级的数据中提取第四层级的数据
                    v3.stream().collect(Collectors.groupingBy(CosmicExcelModel::getFunctionalProcessing)).forEach((k4, v4) -> {
                        CosmicExcelModel cosmicExcelModelStart = v4.get(0);
                        Map<String, Object> dataMap4 = new HashMap<>();
                        dataMap4.put("title4", k4);
                        //构建详细数据
                        //1、 功能详细描述
//                        dataMap4.put("featureDescription", k4);
                        //2、功能界面原型
                        //dataMap4.put("featureInput", cosmicExcelModelStart.getFunctionalInput());
                        //3、用户交互内容
                        List<UserInteractiveContent> uicList = new ArrayList<>();
                        List<CosmicExcelModel> cosmicExcelModelList = v4.stream().filter(cosmicExcelModel -> cosmicExcelModel.getDataMovementType().equalsIgnoreCase("E")).collect(Collectors.toList());
                        for (int i = 0; i < cosmicExcelModelList.size(); i++) {
                            CosmicExcelModel cosmicExcelModel = cosmicExcelModelList.get(i);
                            UserInteractiveContent uic = new UserInteractiveContent();
                            uic.setNumber((i + 1) + "");
                            uic.setDesignation(cosmicExcelModel.getSubFunctionalProcessing());
                            uic.setType("请求");
                            uic.setDescription(cosmicExcelModel.getTriggerEvent());
                            uicList.add(uic);
                        }
                        dataMap4.put("uicList", uicList);

                        //4、用户交互功能
                        List<UserInteractionFunction> uifList = new ArrayList<>();
                        for (int i = 0; i < v4.size(); i++) {
                            CosmicExcelModel cosmicExcelModel = v4.get(i);
                            UserInteractionFunction uic = new UserInteractionFunction();
                            uic.setNumber((i + 1) + "");
                            uic.setDesignation(cosmicExcelModel.getSubFunctionalProcessing());
                            String type = DataMoveTypeEnum.valueOf(cosmicExcelModel.getDataMovementType().toUpperCase()).getValue();
                            uic.setType(type);
                            uic.setDescription(cosmicExcelModel.getTriggerEvent());
                            uifList.add(uic);
                        }
                        dataMap4.put("uifList", uifList);

                        //5、功能交互流程
                        // 提取发起者
                        String initiator = SequenceDescriptionUtil.extractInitiator(cosmicExcelModelStart.getFunctionalUser());
                        dataMap4.put("initiator", StrUtil.isNotBlank(initiator) ? initiator.replace("\n", "") : "");
                        // 提取接收者
                        String receiver = SequenceDescriptionUtil.extractReceiver(cosmicExcelModelStart.getFunctionalUser());
                        dataMap4.put("receiver", StrUtil.isNotBlank(receiver) ? receiver.replace("\n", "") : "");
                        // 提取触发事件
                        String triggerEvent = cosmicExcelModelStart.getTriggerEvent();
                        dataMap4.put("triggerEvent", triggerEvent);
                        // 构建时序图
                        Object[] objects = PlantumlUtil.buildUmlSourceAndDescription(v4);
                        String unlSource = (String) objects[0];
                        List<SequenceDescription> descriptions = (List<SequenceDescription>) objects[1];
                        String sequenceDescription = SequenceDescriptionUtil.getSequenceDescription(descriptions);
                        InputStream inputStream = PlantumlUtil.getInputStream(unlSource);
                        // 插入时序图
                        dataMap4.put("timeSequenceDiagram", Pictures.ofStream(inputStream, PictureType.PNG).create());
                        // 插入时序图描述
                        dataMap4.put("sequenceDescription", sequenceDescription);

                        dataList4.add(dataMap4);
                    });
                });
            });
        });

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList1", dataList1);


        //表格行循环
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("uicList", policy).bind("uifList", policy).build();

        XWPFTemplate template = XWPFTemplate.compile("D:\\DevelopSpace\\XW_Space\\workspace\\COSMIC\\template\\word_template.docx", config).render(dataMap);
        template.writeAndClose(new FileOutputStream("D:\\DevelopSpace\\XW_Space\\workspace\\COSMIC\\template\\COSMIC文档生成-" + LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".docx"));
//        template.writeAndClose(outputStream);
    }
}
